import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:sgy_flutter/ble/base_service.dart';

import '../model/device_info.dart';



class DeviceInfoService extends BaseService {
  static const serviceGuid = ("0000180a-0000-1000-8000-00805f9b34fb");
  static const guidFirmwareRevision = ("00002a26-0000-1000-8000-00805f9b34fb");
  static const guidHardwareRevision = ("00002a27-0000-1000-8000-00805f9b34fb");
  static const guidManufacturerName = ("00002a29-0000-1000-8000-00805f9b34fb");

  BluetoothCharacteristic? _manufacturerNameCharacteristic;
  BluetoothCharacteristic? _hardwareRevisionCharacteristic;
  BluetoothCharacteristic? _firmwareRevisionCharacteristic;

  DeviceInfoService()
      : super(
      serviceGuid: serviceGuid,
      characteristicNotifyGuid: null,
      characteristicReadGuid: null,
      characteristicWriteGuid: null);

  @override
  Future onCleanup() async{
    _manufacturerNameCharacteristic = null;
    _hardwareRevisionCharacteristic = null;
    _firmwareRevisionCharacteristic = null;
  }

  @override
  Future onInitialized(List<BluetoothService> services) async{
    for (final service in services) {
      // 基本信息服务
      if (service.uuid.str128.toLowerCase() == serviceGuid) {
        for (final characteristic in service.characteristics) {
          switch (characteristic.uuid.str128.toLowerCase()) {
            case guidFirmwareRevision:
              _firmwareRevisionCharacteristic = characteristic;
              break;
            case guidHardwareRevision:
              _hardwareRevisionCharacteristic = characteristic;
              break;
            case guidManufacturerName:
              _manufacturerNameCharacteristic = characteristic;
              break;
          }
        }
      }
    }
  }

  Future<DeviceInfo> readDeviceInfo() async {
    final manufacturerName = await _manufacturerNameCharacteristic?.read();
    final hardwareRevision = await _hardwareRevisionCharacteristic?.read();
    final firmwareRevision = await _firmwareRevisionCharacteristic?.read();
    return DeviceInfo(
        manufacturerName: String.fromCharCodes(manufacturerName ?? []),
        hardwareRevision: String.fromCharCodes(hardwareRevision ?? []),
        firmwareRevision: String.fromCharCodes(firmwareRevision ?? []));
  }
}
